    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.model.Distinctive;
import com.click.app.model.DistinctiveName;
import com.click.app.model.LabelValue;
import com.click.app.model.Material;
import com.click.app.model.MeasureUnit;
import com.click.app.model.PurchaseDetail;
import com.click.app.model.StorageMaterial;
import com.click.app.service.DistinctiveManager;
import com.click.app.service.DistinctiveNameManager;
import com.click.app.service.GenericManager;
import com.click.app.service.PurchaseDetailManager;
import com.click.app.service.StorageMaterialManager;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author orgale
 */
public class MaterialAction extends BaseAction {

    private GenericManager<Material, Long> materialManager;
    private GenericManager<MeasureUnit, Long> measureUnitManager;
    private GenericManager<PurchaseDetail, Long> purchaseDetailManager;
    private DistinctiveManager distinctiveManager;
    private DistinctiveNameManager distinctiveNameManager;
    private StorageMaterialManager storageMaterialManager;
    private List materials;
    private Material material;
    private Long id;
    private Long idMeasureUnit;
    private List<Distinctive> distinctivesValues;
    private Long idD;
    private String distinctiveName;
    private String distinctiveValue;
    private Distinctive distinctive;
    private Integer distinctiveIndex;
    private Long idDistinctive;
    private List<Distinctive> distinctiveList;
    private List<Distinctive> distinctivesList;
    private String limit;

    public void setId(Long id) {
        this.id = id;
    }

    public Material getMaterial() {
        return material;
    }

    public void setMaterial(Material material) {
        this.material = material;
    }

    public boolean purchaseDetailFree() {
        boolean resp = true;
        List<PurchaseDetail> pds = purchaseDetailManager.getAll();
        for (PurchaseDetail pd : pds) {
            if (pd.getMaterial().equals(material)) {
                resp = false;
            }
        }
        return resp;
    }

    public StorageMaterial findStorageMaterial(Material m) {
        for (StorageMaterial st : storageMaterialManager.getAll()) {
            if (st.getMaterial().equals(m)) {
                return st;
            }
        }
        return null;
    }

    public String delete() {
        if (purchaseDetailFree()) {
            storageMaterialManager.remove(findStorageMaterial(material).getId());
            //materialManager.remove(material.getId());
            saveMessage(getText("material.deleted"));
        } else {
            errorMessage(getText("material.deleteError"));
        }
        return SUCCESS;
    }

    public String edit() throws Exception {
        System.out.println("Editing material...");

        if (id != null) {

            material = materialManager.get(id);
            distinctiveList = distinctiveManager.findByMaterial(material);
            distinctive = new Distinctive();
            limit = storageMaterialManager.findByIdMaterial(material.getId()).get(0).getLimit().toString();
            getSession().setAttribute("distinctiveList", distinctiveList);
            getSession().setAttribute("deleteDistinctiveList", new ArrayList<Distinctive>());

        } else {
            distinctiveList = new ArrayList<Distinctive>();
            material = new Material();
            distinctive = new Distinctive();
            limit = "0.0";
            getSession().setAttribute("distinctiveList", distinctiveList);
            getSession().setAttribute("deleteDistinctives", new ArrayList<Distinctive>());

        }
        getSession().setAttribute("distinctiveList", distinctiveList);
        return SUCCESS;
    }

    public int findIndex(Long id) {
        int i = -1;
        distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");
        for (Distinctive d : distinctiveList) {
            if (d.getId().equals(id)) {
                i = distinctiveList.indexOf(d);
            }
        }
        System.out.println("retornando index: " + i);
        return i;
    }

    public String deleteDistinctive() {
        distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");
        distinctive = distinctiveList.get(findIndex(idDistinctive));
        if (distinctive.getId() != null) {
            List<Distinctive> deleteDistinctiveList = (List<Distinctive>) getSession().getAttribute("deleteDistinctiveList");
            if (deleteDistinctiveList == null) {
                deleteDistinctiveList = new ArrayList<Distinctive>();
            }
            deleteDistinctiveList.add(distinctive);
            getSession().setAttribute("deleteDistinctiveList", deleteDistinctiveList);
        }
        distinctiveList.remove(distinctive);
        getSession().setAttribute("distinctiveList", distinctiveList);

        distinctive = new Distinctive();
        distinctiveIndex = null;

        return SUCCESS;
    }


    public boolean distinctiveExists(Distinctive di) {
        boolean exists = false;
        distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");
        for (Distinctive d : distinctiveList) {
            if ((d.getName().matches(di.getName())) && (d.getValue().matches(di.getValue()))) {
                exists = true;
            }
        }
        return exists;
    }

    public String saveDistinctive() {
        System.out.println("saving Distinctive ...");
        distinctive = getDistinctiveWithNameAndValue(getDistinctiveName(), getDistinctiveValue());
        if (distinctiveExists(distinctive)) {
            System.out.println("distinctive exists...");
        //errorMessage(getText("distinctive.exists"));
        } else {
            distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");

            if (distinctiveIndex == null) {
                distinctiveList.add(distinctive);
            //saveMessage(getText("distinctive.added"));
            } else {
                distinctiveList.set(distinctiveIndex, distinctive);
                distinctiveIndex = null;
            //saveMessage(getText("distinctive.updated"));
            }
            //System.out.println("primero: " + distinctiveList.get(0).getName() + ", " + distinctiveList.get(0).getValue());
            System.out.println("sar: " + distinctiveList);

            getSession().setAttribute("distinctiveList", distinctiveList);
            distinctive = new Distinctive();
        }
        return SUCCESS;
    }

    public String rdl() {
        distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");

        return SUCCESS;
    }

    public List<LabelValue> getBooleans() {
        List<LabelValue> b = new ArrayList<LabelValue>();
        LabelValue t = new LabelValue(getText("true.available"), "true");
        LabelValue f = new LabelValue(getText("false.unavailable"), "false");
        b.add(t);
        b.add(f);
        return b;
    }

    public boolean validationPasses() {
        Float aux = 0.0f;
        boolean vp = true;
        if (material.getName() == null || material.getName().matches("")) {
            errorMessage("Campo requerido, nombre.");
            vp = false;
        }
        System.out.println("materialunitmeasuere: " + material.getUnitMeasure());
        if (material.getUnitMeasure().getId() == -1) {
            errorMessage("Campo requerido, unidad de medida.");
            vp = false;
        }
        if (getLimit() == null || getLimit().matches("")) {
            errorMessage("Campo requerido, limite.");
            vp = false;
        }
        try {
            if (getLimit() != null && !getLimit().matches("")) {
                aux = Float.parseFloat(getLimit());
            }
            if (aux < 0) {
                errorMessage("El límite es negativo.");
                vp = false;
            }
        } catch (Exception e) {
            errorMessage("El límite se encuentra en formato incorrecto.");
            vp = false;
        }


        //if (getLimit() != null) {
        //    errorMessage("El valor del limite no es un número válido.");
        //    vp = false;
        //}


        if (material.getDistinctives().isEmpty()) {
            errorMessage("Debe asignar al menos un distinctivo.");
            vp = false;
        }

        return vp;
    }

    public String save() throws Exception {
        System.out.println("Saving material...");

        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (material.getId() == null);

        distinctiveList = (List<Distinctive>) getSession().getAttribute("distinctiveList");
        material.getDistinctives().addAll(distinctiveList);
        if (validationPasses()) {
            material = materialManager.save(material);
        } else {
            return ERROR;
        }
        //create Storage for this material

        StorageMaterial sm = new StorageMaterial();
        if (isNew) {
            sm.setMaterial(material);
            sm.setStock(new Double(0));

        } else {
            sm = storageMaterialManager.findByIdMaterial(material.getId()).get(0);

        }

        sm.setLimit(Double.parseDouble(getLimit()));
        sm = storageMaterialManager.save(sm);
        material.setStorageMaterial(sm);

        String key = (isNew) ? "material.added" : "material.updated";
        saveMessage(getText(key));


        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

    public void setMaterialManager(GenericManager<Material, Long> materialManager) {
        this.materialManager = materialManager;
    }

    public void setMeasureUnitManager(GenericManager<MeasureUnit, Long> measureUnitManager) {
        this.measureUnitManager = measureUnitManager;
    }

    public void setDistinctiveManager(DistinctiveManager distinctiveManager) {
        this.distinctiveManager = distinctiveManager;
    }

    public void setDistinctiveNameManager(DistinctiveNameManager distinctiveNameManager) {
        this.distinctiveNameManager = distinctiveNameManager;
    }

    public void setPurchaseDetailManager(PurchaseDetailManager purchaseDetailManager) {
        this.purchaseDetailManager = purchaseDetailManager;
    }

    public void setStorageMaterialManager(StorageMaterialManager storageMaterialManager) {
        this.storageMaterialManager = storageMaterialManager;
    }

    public List getMaterials() {
        return materials;
    }

    public String list() {
        materials = materialManager.getAll();
        return SUCCESS;
    }

    public List<Material> getFullMaterials() {
        List<Material> all = materialManager.getAll();
        for (Material m : all) {
            for (Distinctive d : m.getDistinctives()) {
                m.setName(m.getName() + " " + d.getValue());
            }
        }
        return all;
    }

    public List getMu() {
        List<MeasureUnit> ms = getMeasureUnits();
        for (MeasureUnit m : ms) {
            m.setName(m.getName() + " - " + m.getDescription());
        }
        return ms;
    }

    public List getMeasureUnits() {
        return measureUnitManager.getAll();
    }

    /**
     * @return the idMeasureUnit
     */
    public Long getIdMeasureUnit() {
        return idMeasureUnit;
    }

    /**
     * @param idMeasureUnit the idMeasureUnit to set
     */
    public void setIdMeasureUnit(Long idMeasureUnit) {
        this.idMeasureUnit = idMeasureUnit;
    }

    /**
     * @return the distinctive
     */
    public Distinctive getDistinctive() {
        return distinctive;
    }

    /**
     * @param distinctive the distinctive to set
     */
    public void setDistinctive(Distinctive distinctive) {
        this.distinctive = distinctive;
    }

    /**
     * @return the distinctiveIndex
     */
    public Integer getDistinctiveIndex() {
        return distinctiveIndex;
    }

    /**
     * @param distinctiveIndex the distinctiveIndex to set
     */
    public void setDistinctiveIndex(Integer distinctiveIndex) {
        this.distinctiveIndex = distinctiveIndex;
    }
    private String lst;
    private List lstList = null;
    private List lstList2 = null;

    public List getLstList() {
        System.out.println("Obteining list");
        System.out.println("LIST: " + lstList);
        return lstList;
    }

    public void setLstList(List lstList) {
        this.lstList = lstList;
    }

    public String getLst() {
        return lst;
    }

    public void setLst(String lst) {
        this.lst = lst;
    }

    public List<Distinctive> getDistinctiveList() {
        return distinctiveList;
    }

    /*public List<String> getDistinctiveList(){
    return distinctiveManager.distinctivesNames();
    }*/
    public List<Distinctive> getDistinctivesList() {
        return distinctiveManager.findDistinctives();
    }

    /**
     * @return the idD
     */
    public Long getIdD() {
        return idD;
    }

    /**
     * @param idD the idD to set
     */
    public void setIdD(Long idD) {
        this.idD = idD;
    }
    private List characters;

    public String ajaxSelect() {

        System.out.println("EXECUTE!!!");

        idD = Long.parseLong(getRequest().getParameter("idD"));

        System.out.println("idD: " + idD);

        Distinctive dis = distinctiveManager.get(idD);
        if (dis == null) {
            dis = new Distinctive();
        }
        distinctivesValues = distinctiveManager.findDistinctivesName(dis.getName());
        System.out.println("distinctive values: " + distinctivesValues.size());
        getSession().setAttribute("distinctiveValues", distinctivesValues);
        return SUCCESS;
    }

    public String ajaxS() {
        // Get a list of characters associated with the select TV show

        System.out.println("EXECUTE!!!");

        idD = Long.parseLong(getRequest().getParameter("idD"));

        System.out.println("idD: " + idD);

        Distinctive dis = distinctiveManager.get(idD);
        if (dis == null) {
            dis = new Distinctive();
        }
        distinctivesValues = distinctiveManager.findDistinctivesName(dis.getName());
        return SUCCESS;
    }


    // End execute()
    // This method returns a list of characters for a given TV show.  If no TV
    // show is selected, i.e., initial page view, am empty ArrayList is returned.
    /**
     * @return the characters
     */
    public List getCharacters() {
        System.out.print("getting characters...");
        return characters;
    }

    /**
     * @param characters the characters to set
     */
    public void setCharacters(List characters) {
        this.characters = characters;
    }

    /**
     * @return the distinctivesValue
     */
    public List<Distinctive> getDistinctivesValues() {
        return distinctivesValues;
    }

    /**
     * @param distinctivesValue the distinctivesValue to set
     */
    public void setDistinctivesValues(List<Distinctive> distinctivesValue) {
        this.distinctivesValues = distinctivesValue;
    }

    /**
     * @param distinctiveList the distinctiveList to set
     */
    public void setDistinctiveList(List<Distinctive> distinctiveList) {
        this.distinctiveList = distinctiveList;
    }

    /**
     * @return the distinctiveValue
     */
    public String getDistinctiveValue() {
        return distinctiveValue;
    }

    /**
     * @param distinctiveValue the distinctiveValue to set
     */
    public void setDistinctiveValue(String distinctiveValue) {
        this.distinctiveValue = distinctiveValue;
    }

    /**
     * @param distinctivesList the distinctivesList to set
     */
    public void setDistinctivesList(List<Distinctive> distinctivesList) {
        this.distinctivesList = distinctivesList;
    }

    /**
     * @return the idDistinctive
     */
    public Long getIdDistinctive() {
        return idDistinctive;
    }

    /**
     * @param idDistinctive the idDistinctive to set
     */
    public void setIdDistinctive(Long idDistinctive) {
        this.idDistinctive = idDistinctive;
    }

    public String helpList() {
        return SUCCESS;
    }

    public String help() {
        return SUCCESS;
    }

    /**
     * @return the limit
     */
    public String getLimit() {
        System.out.println("limitg: " + limit);
        return limit;
    }
    private String defaultItem;
    private String doubleDefaultItem;

    /**
     * @param limit the limit to set
     */
    public void setLimit(String limit) {
        this.limit = limit;
    }

    /**
     * @return the distinctiveName
     */
    public String getDistinctiveName() {
        return distinctiveName;
    }

    /**
     * @param distinctiveName the distinctiveName to set
     */
    public void setDistinctiveName(String distinctiveName) {
        this.distinctiveName = distinctiveName;
    }

    public List<DistinctiveName> getDistinctiveNames() {
        return distinctiveNameManager.getAll();
    }

    /**
     * @return the defaultItem
     */
    public String getDefaultItem() {
        return defaultItem;
    }

    /**
     * @param defaultItem the defaultItem to set
     */
    public void setDefaultItem(String defaultItem) {
        this.defaultItem = defaultItem;
    }

    /**
     * @return the doubleDefaultItem
     */
    public String getDoubleDefaultItem() {
        return doubleDefaultItem;
    }

    /**
     * @param doubleDefaultItem the doubleDefaultItem to set
     */
    public void setDoubleDefaultItem(String doubleDefaultItem) {
        this.doubleDefaultItem = doubleDefaultItem;
    }

    public Distinctive getDistinctiveWithNameAndValue(String n, String v) {
        Distinctive d = null;
        for (Distinctive di : distinctiveManager.getAll()) {
            if ((di.getValue().matches(v)) && (di.getName().matches(n))) {
                d = di;
            }
        }
        return d;
    }
}